package edu.scau.divineplace.config.global.validate.validator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import edu.scau.divineplace.config.global.validate.annotation.NotContainBanWord;
import edu.scau.divineplace.entity.dos.BanWordDO;
import edu.scau.divineplace.service.ImportMapperService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Author: x1aolone
 * @Date: 2021/1/14 17:03
 * 判断评论是否有禁用词的检验器
 */
public class NotContainBanWordValidator implements ConstraintValidator<NotContainBanWord, String> {

    @Autowired
    private ImportMapperService importMapperService;

    @Override
    public void initialize(NotContainBanWord constraintAnnotation) {
        // do nothing
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.equals("")) {
            return true;
        }
//        //获取默认提示信息
//        String defaultConstraintMessageTemplate = context.getDefaultConstraintMessageTemplate();
//        //禁用默认提示信息
//        context.disableDefaultConstraintViolation();
//        //设置提示语
//        context.buildConstraintViolationWithTemplate("can not contains blank").addConstraintViolation();
        QueryWrapper<BanWordDO> query = Wrappers.<BanWordDO>query()
                .select("id")
                .gt("POSITION(word in '" + value + "')", 0);
        Integer count = importMapperService.banWordMapper.selectCount(query);
        return count == 0;
    }
}
